package com.example.agron.user;

import com.example.agron.common.http.UserResponse;
import com.example.agron.common.utils.PageChunk;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.Month;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class UserService {

    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }


    public UserResponse<User> getUsers(int offset, int pageSize, String field){
        Page<User> filterUsers = userRepository.findAll(PageRequest.of(offset, pageSize).withSort(Sort.by(field)));
        UserResponse users = UserResponse.success(filterUsers.getContent());
        return users;
    }

    /*public UserResponse<User> searchUsers(int offset, int pageSize, String name, String email, String gender, String field){
        Pageable pageable = PageRequest.of(offset, pageSize).withSort(Sort.by(field));
        Page<User> filterUsers = userRepository.findUserByNameContainsAndEmailContainsAndGenderContains(name, email, gender, pageable);
        UserResponse users = UserResponse.success(filterUsers);
        return users;
    }*/

    public UserResponse<User> searchUsers(int offset, int pageSize, String name, String email, String gender, String fieldBy, String field){
        PageChunk pageChunk = new PageChunk<>();
        Pageable pageable = PageRequest.of(offset, pageSize, Sort.by(Sort.Direction.fromString(field), String.valueOf(fieldBy)));
        Page<User> filterUsers = userRepository.findUserByNameContainsAndEmailContainsAndGenderContains(name, email, gender, pageable);

        pageChunk.setContent(filterUsers.getContent());
        pageChunk.setTotal(filterUsers.getTotalElements());
        pageChunk.setTotalPages(filterUsers.getTotalPages());
        pageChunk.setPageNumber(filterUsers.getNumber());
        pageChunk.setPageSize(filterUsers.getSize());
        pageChunk.setNumberOfElement(filterUsers.getNumberOfElements());

        UserResponse users = UserResponse.success(pageChunk);
        return users;
    }


    public List<User> findUsersWithSorting(String field){
        return userRepository.findAll(Sort.by(Sort.Direction.ASC, field));
    }


    public Page<User> findUsersWithPagination(int offset, int pageSize){
        Page<User> users = userRepository.findAll(PageRequest.of(offset, pageSize));
        return users;
    }


    public ResponseEntity<User> getUserById(Long userId){
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new IllegalStateException("student with id" + userId + " does not exists"));
        return ResponseEntity.ok().body(user);
    }

    public void addNewUser(User user){
        Optional<User> userOptional = userRepository.findUserByEmail(user.getEmail());
        if(userOptional.isPresent()){
            throw new IllegalStateException("email taken");
        }
        userRepository.save(user);
        System.out.println(user);
    }

    public void deleteUser(Long userId){
        boolean exists = userRepository.existsById(userId);
        if(!exists){
            throw new IllegalStateException("student with id" + userId + " does not exists");
        }
        userRepository.deleteById(userId);
    }

    public void batchDeleteUser(String userIds){
        if(userIds == null || userIds == ""){
            throw new IllegalStateException("student with id" + userIds + " does not exists");
        }
        List<Long> collect = Arrays.stream(userIds.split(",")).map(Long::parseLong).collect(Collectors.toList());
        userRepository.deleteAllById(collect);
    }

    @Transactional
    public UserResponse<User> updateUser(Long userId, String name, String password, String email, String avatarUrl, String gender, LocalDate dob){

        System.out.println(avatarUrl);

        User user = userRepository.findById(userId)
                .orElseThrow(()-> new IllegalStateException(
                        "user with id"+ userId + "does not exists"
                ));
        if (name != null && name.length() > 0 && !Objects.equals((user.getName()), name)){
            user.setName(name);
        }

        if (password != null && password.length() > 0 && !Objects.equals((user.getPassword()), password)){
            user.setPassword(password);
        }

        if (email != null && email.length() > 0 && !Objects.equals((user.getEmail()), email)){
            user.setEmail(email);
        }

        if (avatarUrl != null && !Objects.equals((user.getAvatarUrl()), avatarUrl)){
            user.setAvatarUrl(avatarUrl);
        }

        if (gender != null && !Objects.equals((user.getGender()), gender)){
            user.setGender(gender);
        }

        if (dob != null && !Objects.equals((user.getDob()), dob)){
            user.setDob(dob);
        }

        return UserResponse.success(user);
    }


    public void uploadUserAvatar(MultipartFile headerImage, Model model){

        if (headerImage == null) {
            model.addAttribute("error", "您还没有选择图片");
            return;
        }

        String filename = headerImage.getOriginalFilename();
        //截取文件的后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        /*if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件的格式不正确");
            return "/site/setting";
        }*/

        //生成随机的文件名称
        filename = suffix;
        //确定文件存放的路径
        File dest = new File("/" + filename);
        try {
            //存储文件
            headerImage.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败，服务器发生异常", e);
        }
        //更新当前用户头像的路径（Web访问路径）
        //http://localhost:8888/community/user/header/XXX.png
        /*User user = user.getUser();*/
        String url = "/user/header/" + filename;

        return;
    }


    public ResponseEntity<String> uploadUserImage(MultipartFile file, Model model) {

        // 获取上传文件名
        String filename = file.getOriginalFilename();
        // 定义上传文件保存路径
        String path = "D://tmp//";
        // 新建文件
        File filepath = new File(path, filename);
        // 判断路径是否存在，如果不存在就创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        try {
            // 写入文件
            file.transferTo(new File("D://tmp//" + file.getOriginalFilename()));
            /*file.transferTo(new File(path + File.separator + filename));*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将src路径发送至html页面
        //model.addAttribute("filename", "/images/rotPhoto/" + filename);

        /*System.out.println(file.getContentType());
        System.out.println(file.getSize());
        System.out.println(file.getOriginalFilename());*/
        System.out.println(filepath.getAbsolutePath());

        return ResponseEntity.ok().body(filepath.getAbsolutePath());
    }


    public void login(User user){
        /*userRepository.*/
    }
}
